package com.wsh.crawler.service.impl;


import com.wsh.crawler.entity.CommonPage;
import com.wsh.crawler.entity.News;
import com.wsh.crawler.repository.NewsRepository;
import com.wsh.crawler.service.NewsService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class NewsServiceImpl implements NewsService {

    private final static Logger LOGGER = LoggerFactory.getLogger(NewsServiceImpl.class);

    @Resource
    private NewsRepository newsRepository;

    /**
     * 获取资讯列表
     * @param updatedAt 更新时间戳（秒）
     * @param pageNum 页码
     * @param pageSize 页大小
     * @return 分页结果
     */
    @Override
    public CommonPage<News> getNewsList(Long updatedAt, Integer pageNum, Integer pageSize) {
        try {
            // 创建分页对象，注意MongoDB页码从0开始
            Pageable pageable = PageRequest.of(pageNum - 1, pageSize);

            Page<News> newsPage;

            if (updatedAt != null) {
                // 将时间戳转换为Date对象
                Date updateTime = new Date(updatedAt * 1000L);
                LOGGER.info("【资讯列表】查询 {} 之后更新的资讯数据", updateTime);

                // 查询指定时间之后的数据
                newsPage = newsRepository.findByCrawlTimeAfterOrderByCrawlTimeDesc(updateTime, pageable);
            } else {
                // 查询所有数据
                LOGGER.info("【资讯列表】查询所有资讯数据，页码：{}，页大小：{}", pageNum, pageSize);
                newsPage = newsRepository.findAllByOrderByCrawlTimeDesc(pageable);
            }

            // 转换为CommonPage格式
            CommonPage<News> result = new CommonPage<>();
            result.setPageNum(pageNum);
            result.setPageSize(pageSize);
            result.setTotalPage((int) Math.ceil((double) newsPage.getTotalElements() / pageSize));
            result.setTotal(newsPage.getTotalElements());
            result.setList(newsPage.getContent());
            return result;
        } catch (Exception e) {
            LOGGER.error("【资讯列表】获取资讯列表失败", e);
            throw new RuntimeException("获取资讯列表失败: " + e.getMessage());
        }
    }
}
